<template>
  <div class="app-container">
    <el-form ref="freightForm" :model="freightForm" :rules="freightRules" label-width="100px" class="margin-right-20">
      <el-form-item label="模板名称:" prop="name">
        <el-input v-model="freightForm.name" placeholder="请输入运费模板名称" maxlength="30"/>
      </el-form-item>
      <el-form-item label="是否包邮:" prop="freeShipping">
        <el-radio-group v-model="freightForm.freeShipping" @change="freeShippingChange">
          <el-radio :label="true">卖家承担运费</el-radio>
          <el-radio :label="false">自定义运费</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="计价方式:" prop="pricingMethod">
        <el-radio-group v-model="freightForm.pricingMethod">
          <el-radio :label="conditionType.PIECE.id">按件数</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="运送方式:">
        <div class="red">除指定地区外，其余地区的运费采用“默认运费”</div>
        <template v-for="type in shippingType">
          <div :key="type.id">
            <el-checkbox v-model="type.selected" :disabled="freightForm.freeShipping">{{ type.name }}</el-checkbox>
            <el-card v-if="type.selected" class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                默认全国:&nbsp;&nbsp;
                <el-tooltip class="item" effect="dark" content="输入1至9999的整数" placement="top">
                  <el-input v-model="type.defaultPricing.firstPiece" class="w100" placeholder="首件" maxlength="5"/>
                </el-tooltip>&nbsp;&nbsp;
                件内&nbsp;&nbsp;
                <el-tooltip class="item" effect="dark" content="应输入0.00至9999.99的数字,小数保留两位" placement="top">
                  <el-input v-model="type.defaultPricing.firstPrice" class="w100" placeholder="首运费" maxlength="5"/>
                </el-tooltip>&nbsp;元,
                每增加&nbsp;&nbsp;
                <el-tooltip class="item" effect="dark" content="输入1至9999的整数" placement="top">
                  <el-input v-model="type.defaultPricing.nextPiece" class="w100" placeholder="续件" maxlength="5"/>
                </el-tooltip>&nbsp;件,&nbsp;&nbsp;
                增加运费&nbsp;&nbsp;
                <el-tooltip class="item" effect="dark" content="应输入0.00至999.99的数字,且不大于默认运费,小数保留两位" placement="top">
                  <el-input v-model="type.defaultPricing.nextPrice" class="w100" placeholder="续运费" maxlength="5"/>
                </el-tooltip>&nbsp;元
              </div>
              <el-table :data="type.pricings">
                <el-table-column label="运送到">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="运送地址如果是全省选择省份选项即可" placement="top">
                      <el-cascader v-if="showCas" :ref="'cascader'+scope.$index" v-model="scope.row.citys" :options="cities" :show-all-levels="false" :props="props" @change="chooseShippingCity(scope)" @remove-tag="removeCityTag(scope,$event)"/>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column :label="'首件数(件)'" prop="firstPiece" width="100">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="输入1至9999的整数" placement="top">
                      <el-input v-model="scope.row.firstPiece" maxlength="5" placeholder="首件"/>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="firstPrice" label="首费(元)" width="100">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="应输入0.00至9999.99的数字,小数保留两位" placement="top">
                      <el-input v-model="scope.row.firstPrice" maxlength="5" placeholder="首运费"/>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column :label="'续件数(件)'" prop="nextPiece" width="100">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="输入1至9999的整数" placement="top">
                      <el-input v-model="scope.row.nextPiece" maxlength="5" placeholder="续件"/>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="nextPrice" label="续费(元)" width="100">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="应输入0.00至999.99的数字,且不大于默认运费,小数保留两位" placement="top">
                      <el-input v-model="scope.row.nextPrice" maxlength="5" placeholder="续运费"/>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template slot-scope="scope">
                    <el-link v-permission="['freight:edit']" :underline="false" type="primary" class="margin-left-10" @click="removeExpressPricing(scope, type)">删除</el-link>
                  </template>
                </el-table-column>
              </el-table>
              <el-link :underline="false" type="primary" class="margin-left-10" @click="addExpressPricing(type)">为指定地区城市设置运费</el-link>
            </el-card>
          </div>
        </template>
      </el-form-item>
      <el-divider/>
      <el-form-item>
        <el-checkbox v-model="freightForm.freeConditions" :disabled="freightForm.freeShipping" @change="freeConditionsChange">指定包邮条件(可选)</el-checkbox>
        <el-table v-if="freightForm.freeConditions" :data="freightForm.conditions">
          <el-table-column label="包邮地区">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="运送地址如果是全省选择省份选项即可" placement="top">
                <el-cascader v-if="showCas" :ref="'cascaderCondition'+scope.$index" v-model="scope.row.citys" :options="cities" :show-all-levels="false" :props="props" @change="chooseConditionCity(scope)" @remove-tag="removeCityTag(scope,$event)"/>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="运送方式" width="80" align="center">
            <template slot-scope="scope">
              快递
            </template>
          </el-table-column>
          <el-table-column label="包邮方式" prop="pricingMethod" width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.pricingMethod" placeholder="请选择包邮方式">
                <el-option v-for="item in conditionType" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column width="350">
            <template slot-scope="scope">
              <div v-if="scope.row.pricingMethod=== conditionType.PIECE.id">
                满 <el-tooltip class="item" effect="dark" content="输入1至9999的整数" placement="top">
                  <el-input v-model="scope.row.pieces" class="w100" placeholder="件数" maxlength="5"/>
                </el-tooltip> 件包邮
              </div>
              <div v-if="scope.row.pricingMethod=== conditionType.MONEY.id">
                满 <el-tooltip class="item" effect="dark" content="应输入0.00至9999.99的数字,小数保留两位" placement="top">
                <el-input v-model="scope.row.prices" class="w100" placeholder="金额" maxlength="5"/></el-tooltip> 元包邮
              </div>
              <div v-if="scope.row.pricingMethod=== conditionType.ALL.id">
                满 <el-tooltip class="item" effect="dark" content="输入1至9999的整数" placement="top">
                  <el-input v-model="scope.row.pieces" class="w100" placeholder="件数" maxlength="5"/>
                </el-tooltip> 件或
                满 <el-tooltip class="item" effect="dark" content="应输入0.00至9999.99的数字,小数保留两位" placement="top">
                <el-input v-model="scope.row.prices" class="w100" placeholder="金额" maxlength="5"/></el-tooltip> 元以上包邮
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-link v-if="scope.$index!=0" :underline="false" type="primary" class="margin-left-10" @click="removeFreeCondition(scope)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-link v-if="freightForm.freeConditions" :underline="false" type="primary" class="margin-left-10" @click="addFreeCondition">为指定地区城市设置包邮</el-link>
      </el-form-item>
      <el-form-item>
        <el-button v-permission="['freight:add','freight:edit']" type="primary" @click="submitFreight">提交</el-button>
        <el-button v-permission="['freight:add','freight:edit']" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style>
  .el-card__body{padding:0px;}
  .w100{width:80px;}
  .el-drawer__header span{ outline: 0 }
  .el-drawer__body{overflow-y: auto}
  .el-cascader{width:100%;}
</style>
<script>
import { FreightTemplateService } from '@/api/ProductService'
import { Alert, Notify } from '@/utils/notify'
import { Validator } from '@/utils/validate'
import cityJson from '@/assets/city.json'

class TemplatePricing {
  constructor() {
    this.shippingMethod = undefined
    this.citys = undefined
    this.cityNames = undefined
    this.firstPiece = undefined
    this.nextPiece = undefined
    this.firstPrice = undefined
    this.nextPrice = undefined
    this.defaults = undefined
  }
}
class TemplateFreeCondition {
  constructor() {
    this.shippingMethod = undefined
    this.pricingMethod = undefined
    this.citys = undefined
    this.cityNames = undefined
    this.pieces = undefined
    this.prices = undefined
  }
}
const expressPricing = new TemplatePricing()
expressPricing.shippingMethod = 1
expressPricing.defaults = true

export default {
  name: 'Freight',
  data() {
    return {
      showCas: true,
      isSave: true, props: { label: 'name', value: 'id', multiple: true, checkStrictly: true }, cities: cityJson,
      shippingType: { EXPRESS: { id: 1, name: '快递', selected: false, defaultPricing: expressPricing, pricings: [] }},
      conditionType: { PIECE: { id: 1, name: '件数' }, MONEY: { id: 2, name: '金额' }, ALL: { id: 5, name: '件数+金额' }},
      freightForm: { name: undefined, freeShipping: true, freeConditions: false, pricingMethod: 1, pricings: [], conditions: [] },
      freightRules: {
        name: [{ required: true, message: '运费模板名称不能为空!', trigger: 'blur' }]
      }
    }
  },
  created() {
    const templateId = this.$route.query.templateId
    if (templateId) {
      this.loadFreightTemplate(templateId)
      this.isSave = false
    }
  },
  methods: {
    loadFreightTemplate(templateId) {
      FreightTemplateService.getFreight(templateId).then(result => {
        this.freightForm = result
        if (this.freightForm) {
          if (this.freightForm.pricings) {
            this.freightForm.pricings.forEach(pricing => {
              for (const key in this.shippingType) {
                const type = this.shippingType[key]
                if (pricing.shippingMethod === type.id) {
                  type.selected = true
                  const citys = pricing.citys
                  const cityNames = pricing.cityNames
                  let cityArray = []
                  let cityNameArray = []
                  if (citys) {
                    cityArray = citys.split(',')
                    cityNameArray = cityNames.split(',')
                  }
                  for (let i = 0; i < cityArray.length; i++) {
                    const item = cityArray[i]
                    cityArray[i] = item.split('-')
                  }
                  pricing.citys = cityArray
                  pricing.cityNames = cityNameArray
                  if (pricing.defaults) {
                    type.defaultPricing = pricing
                  } else {
                    type.pricings.push(pricing)
                  }
                }
              }
            })
          }
          if (this.freightForm.conditions) {
            this.freightForm.conditions.forEach(condition => {
              const citys = condition.citys
              const cityNames = condition.cityNames
              let cityArray = []
              let cityNameArray = []
              if (citys) {
                cityArray = citys.split(',')
                cityNameArray = cityNames.split(',')
              }
              for (let i = 0; i < cityArray.length; i++) {
                const item = cityArray[i]
                cityArray[i] = item.split('-')
              }
              condition.citys = cityArray
              condition.cityNames = cityNameArray
            })
          }
        }
      })
    },
    freeShippingChange(val) {
      const message = val ? '选择“卖家承担运费”后，所有区域的运费将设置为0元且原运费设置无法恢复，请保存原有运费设置!' : '您的运费设置将变为未设置状态，请设置运费。'
      this.$confirm(message, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        if (val) {
          for (const key in this.shippingType) {
            this.shippingType[key].selected = false
            this.freightForm.freeConditions = false
          }
        }
      }).catch(() => {
        this.freightForm.freeShipping = !val
        return false
      })
    },
    addExpressPricing(type) {
      const pricing = new TemplatePricing()
      pricing.defaults = false
      pricing.shippingMethod = type.id
      type.pricings.push(pricing)
    },
    removeExpressPricing(scope, type) {
      const index = scope.$index
      type.pricings.splice(index, 1)
    },
    chooseShippingCity(scope) {
      const index = scope.$index
      const nodes = this.$refs['cascader' + index][0].getCheckedNodes()
      const citys = []
      const cityNames = []
      nodes.forEach(node => {
        citys.push(node.path)
        cityNames.push(node.label)
      })
      scope.row.citys = citys
      scope.row.cityNames = cityNames
    },
    checkExpressData() {
      let flag = true
      if (!this.freightForm.freeShipping) {
        // 自定义运费需要校验运费数据
        const length = this.freightForm.pricings.length
        if (length === 0) {
          Alert.warn(this, '请选择配送方式!')
          flag = false
          return
        }
        this.freightForm.pricings.forEach(pricing => {
          if (!pricing.defaults && !pricing.cityNames && !pricing.citys) {
            Alert.warn(this, '请选择地区!')
            flag = false
            return
          }
          if (!Validator.isPositiveInteger(pricing.firstPiece)) {
            Alert.warn(this, '首件数必须是大于0的整数!')
            flag = false
            return
          }
          if (!Validator.isPositiveFloat(pricing.firstPrice)) {
            Alert.warn(this, '首件运费必须是大于或等于0的数!')
            flag = false
            return
          }
          if (!Validator.isPositiveInteger(pricing.nextPiece)) {
            Alert.warn(this, '续件数必须是大于0的整数!')
            flag = false
            return
          }
          if (!Validator.isPositiveFloat(pricing.nextPrice)) {
            Alert.warn(this, '续件运费用必须是大于或等于0的数!')
            flag = false
            return
          }
          if (parseFloat(pricing.firstPrice) < parseFloat(pricing.nextPrice)) {
            Alert.warn(this, '续费不能大于首费!')
            flag = false
            return
          }
        })
      }
      if (this.freightForm.freeConditions) {
        if (this.freightForm.conditions.length < 1) {
          Alert.warn(this, '请选择地区!')
          return false
        }
        this.freightForm.conditions.forEach(condition => {
          if (!condition.cityNames && !condition.citys) {
            Alert.warn(this, '请选择地区!')
            flag = false
            return
          }
          if (condition.pricingMethod === this.conditionType.PIECE.id || condition.pricingMethod === this.conditionType.ALL.id) {
            if (!Validator.isPositiveInteger(condition.pieces)) {
              Alert.warn(this, '件数必须是大于0的整数!')
              flag = false
              return
            }
          }
          if (condition.pricingMethod === this.conditionType.MONEY.id || condition.pricingMethod === this.conditionType.ALL.id) {
            if (!Validator.isPositiveFloat(condition.prices)) {
              Alert.warn(this, '金额必须是大于或等于0的数!')
              flag = false
              return
            }
          }
        })
      }
      return flag
    },
    freeConditionsChange() {
      let selectShipping = false
      for (const key in this.shippingType) {
        if (this.shippingType[key].selected) {
          selectShipping = true
        }
      }
      if (!selectShipping) {
        this.freightForm.freeConditions = false
        Alert.warn(this, '至少选择一项非自提的运送方式!')
        return
      }
      if (this.freightForm.conditions < 1) {
        this.addFreeCondition()
      }
    },
    addFreeCondition() {
      const condition = new TemplateFreeCondition()
      condition.shippingMethod = this.shippingType.EXPRESS.id
      condition.pricingMethod = this.conditionType.PIECE.id
      this.freightForm.conditions.push(condition)
    },
    removeFreeCondition(scope) {
      const index = scope.$index
      this.freightForm.conditions.splice(index, 1)
    },
    chooseConditionCity(scope) {
      const index = scope.$index
      const nodes = this.$refs['cascaderCondition' + index].getCheckedNodes()
      const citys = []
      const cityNames = []
      nodes.forEach(node => {
        citys.push(node.path)
        cityNames.push(node.label)
      })
      scope.row.citys = citys
      scope.row.cityNames = cityNames
    },
    removeCityTag(scope, event) {
      this.showCas = false
      const citys = scope.row.citys
      const cityNames = scope.row.cityNames
      if (citys.includes(event)) {
        const index = citys.indexOf(event, citys)
        citys.splice(index, 1)
        cityNames.splice(index, 1)
      }
      this.$nextTick(() => {
        this.showCas = true
      })
    },
    resetForm() {
      this.$refs['freightForm'].resetFields()
    },
    submitFreight() {
      this.$refs['freightForm'].validate(valid => {
        if (valid) {
          let pricings = []
          for (const key in this.shippingType) {
            const pricing = this.shippingType[key]
            if (pricing.selected) {
              if (pricing.defaultPricing) {
                pricings.push(pricing.defaultPricing)
              }
              if (pricing.pricings && pricing.pricings.length > 0) {
                pricings = pricings.concat(pricing.pricings)
              }
            }
          }
          this.freightForm.pricings = pricings
          if (!this.checkExpressData()) {
            return
          }
          const data = JSON.parse(JSON.stringify(this.freightForm))
          // 提交前将选择的地区转换为后台识别的格式
          data.pricings.forEach(pricing => {
            const citys = pricing.citys
            const cityNames = pricing.cityNames
            const cityResult = []
            if (citys) {
              citys.forEach(city => {
                cityResult.push(city.join('-'))
              })
              pricing.citys = cityResult.join(',')
              pricing.cityNames = cityNames.join(',')
            }
          })
          data.conditions.forEach(condition => {
            const citys = condition.citys
            const cityNames = condition.cityNames
            const cityResult = []
            if (citys) {
              citys.forEach(city => {
                cityResult.push(city.join('-'))
              })
              condition.citys = cityResult.join(',')
              condition.cityNames = cityNames.join(',')
            }
          })
          if (this.isSave) {
            FreightTemplateService.addFreight(data).then(() => {
              Notify.success(this, '保存成功!')
              this.resetForm()
              this.$router.push({ path: '/mall/freight' })
            })
          } else {
            FreightTemplateService.editFreight(data).then(() => {
              Notify.success(this, '保存成功!')
              this.resetForm()
              this.$router.push({ path: '/mall/freight' })
            })
          }
        }
      })
    }
  }
}
</script>
